/**
 *
 * @author groupA   
 */
package com.groupa.project1.chat;

import com.groupa.project1.chat.interfaces.InstantMessage;
import com.groupa.project1.database.interfaces.XmlDbDataSource;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.Scanner;
import java.util.logging.Logger;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.FromContainsFilter;
import org.jivesoftware.smack.filter.NotFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smack.XMPPException;


public class InstantMessageClass implements InstantMessage{
    
    private MultiUserChat chat = null;    
    private PacketFilter filter = null;   
    private XMPPConnection con;
    private String login_name = "";
    private static InstantMessage msn = null;
    private static Logger log;
    private ListenerClass L;

    private boolean testSearchProfile;
    private boolean testUserContent;
    private boolean testSearchResult;
    
    private static Properties Prop;
    private static Properties Actions;
    
    private InstantMessageClass(){   
        Prop = getConfig("properties.properties");
        Actions = getConfig("actions.properties");
    /* Constructor */
    }
    
    public synchronized static InstantMessage GetInstance(){
        /* Usamos el patron de diseño singelton */
        if(msn == null){
            msn = new InstantMessageClass();
            log = Logger.getLogger("Testlog");
        }
        
        return msn;
    }
    
     private static Properties getConfig(String file){
            /**
             * método para leer el fichero de configuración
            */
            Properties P = new Properties();
             /* Obtenemos el input stream */
            InputStream In = XmlDbDataSource.class.getClassLoader().getResourceAsStream(file);
            InputStreamReader IR = null;

            try{
                /* Obtenemos el archivo  */
                IR = new InputStreamReader(In, "UTF8");
                P.load(IR);

            } catch(Exception ex) {
               
                }
            /* Devolvemos el fichero de propiedades */
            return P;
    }

    public static Properties getActionsStatic(){
            return Actions;
    }
    public static Properties getPropertiesStatic(){
            return Prop;
    }
    
    public XMPPConnection getCon() {  
        return con;
    }
     public MultiUserChat getChat() {  
        return chat;
    }
    public ListenerClass getListener() {
        return L;
    } 
    public static Logger getLog() {  
        return log;
    }
    
    /* funciones para testear */
    public boolean getstatusSp() {  
        return testSearchProfile;
    }
    public boolean getstatusUC() {  
        return testUserContent;
    }
    public boolean getstatusSR() {  
       return testSearchResult;
    }
     public void setstatusSp() {  
        testSearchProfile = true;
    }
    public void setstatusUC() {  
        testUserContent = true;
    }
    public void setstatusSR() {  
        testSearchResult = true;
    }
    /*                        */ 
    
    public boolean logout() {
        if (con!= null) {
          con.disconnect();
          log.info("Desconectado con éxito");
          return true;
        } 
        return false;
    }
    
    public boolean login(final String LoginName, final String LoginPassword, String resource) { 
        /* Función login */
        this.login_name = LoginName;
        
        boolean flag = false;
        
        try {
            /*Create the connection to the google talk*/
            ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
            config.setSASLAuthenticationEnabled(true);
            config.setReconnectionAllowed(true);
            con = new XMPPConnection(config);
            con.connect();
            /* Conectamos a google talk*/
            con.login(LoginName, LoginPassword, resource);
            /*Para hacer el test desactivamos el filtro para enviarnos un mensaje a nosotros mismos*/
            filter = new AndFilter(new PacketTypeFilter(Message.class),new NotFilter(new FromContainsFilter(con.getUser()))); //cambiar para test
        
            con.createPacketCollector(filter);
            /* Inicializamos el grupo de chat */

            chat = new MultiUserChat(con, LoginName + "'s Chat");

            this.L = new ListenerClass(chat, con, msn, log);
            con.addPacketListener(L, filter);

            flag = true;
        
        } catch (Throwable ex) {
                ex.printStackTrace();
                flag = false;
        }

        return flag;
    }

    public boolean send(GenericMessageClass GMC) {
          
              boolean flag = false;
              
          try {
                /* Creamos un nuevo mensaje y le entramos el origen y destino*/
                 Message msg = new Message();
               log.info("TO:" + GMC.getDestination() + "/" + "Home");
               msg.setTo(GMC.getDestination()+"/" + "Home");
               msg.setProperty("generic", GMC);
               msg.setPacketID("pepelucas");
               
               msg.setBody("pepito");
               msg.setProperty("fecha", new Date());
               chat.sendMessage(msg);
                flag = true;
                
            } catch (Exception ex) {
                 ex.printStackTrace();
            }
          
        return flag;
    }
    
    public Roster GetContacts(){ 
        /* Obtenemos los contactos */
   return con.getRoster();
    
  
    }
    

}